/**
 * @description 首页 controller
 * @author 刘煎蛋
 */

const { REG_FOR_AT_WHO, PAGE_SIZE } = require('../conf/constant');
const { getUserInfo } = require('../services/user');
const { createBlog, getFollowersBlogList } = require('../services/blog');
const { createAtRelation } = require('../services/at-relation');
const { SuccessModel, ErrorModel } = require('../model/ResModel');
const { createBlogFailInfo } = require('../model/ErrorInfo');

/**
 * 
 * @param {*} userId  用户id
 * @param {*} content  微博文案
 * @param {*} image   图片
 */
async function create({ userId, content, image }) {
    
    let atUserNameList = [];
    content = content.replace( REG_FOR_AT_WHO, ( matchStr, nickName, userName ) => {
        atUserNameList.push(userName);
        return matchStr;
    })

    const atUserList = await Promise.all( 
        atUserNameList.map( userName => getUserInfo(userName ))
    )
    
    const atUserIdList = atUserList.map( user => user.id );
    console.log( '请紧急呼叫', userId, atUserIdList );

    try {

        const blog = await createBlog({
            userId,
            content,
            image
        })

        // 创建 @关系
        await Promise.all(atUserIdList.map( userId => {
            createAtRelation( blog.id, userId );
        }))

        return new SuccessModel(blog);

    } catch( err ) {
        return new ErrorModel(createBlogFailInfo);
    }

}

/**
 * 获取首页微博列表
 * @param {*} userId 用户id
 * @param {*} pageIndex 页数
 */
async function getHomeBlogList( userId, pageIndex = 0 ) {
    const result = await getFollowersBlogList({
        userId,
        pageIndex,
        pageSize: PAGE_SIZE
    })

    const { count, blogList } = result;

    return new SuccessModel({
        isEmpty: blogList.length === 0,
        blogList,
        pageSize: PAGE_SIZE,
        pageIndex,
        count
    })

}

module.exports = {
    create,
    getHomeBlogList
}